﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Specialized;

using Estimate.Common.DataFileFinder;
using Estimate.Common.DataImporter;
using System.Configuration;
using System.IO;
using Estimate.Common.Estimate;
using Estimate.Common.Entity;
using Estimate.Common.DBFieldTypes;
using Estimate.Common.Repository;
using System.Reflection;
using log4net;


namespace Estimate.Common
{
    /// <summary>
    /// 将导入数据文件及后续处理的函数整合在一起，方便调用方调用
    /// </summary>
    public class DataImporterCombiner
    {
        public  Semier semier;

        public static ILog Logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public NameValueCollection AppSettings;
        
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dbConnectionString">数据库连接字符串</param>
        public DataImporterCombiner(NameValueCollection appSettings)
        {
            AppSettings = appSettings;
            semier = new Semier(AppSettings["ConnectionString"]);
        }

        /// <summary>
        /// 导入实况数据
        /// </summary>
        /// <param name="info">导入数据信息</param>
        /// <param name="dt">日期</param>
        /// <param name="dirPath">目录</param>
        /// <param name="finder">文件发现类</param>
        /// <param name="importer">文件导入类</param>
        public void importData(string info, DateTime dt, string dirPath, IDataFileFinder finder, IDataImporter importer, bool assertHaseFile)
        {
            Logger.Info(info);
            Logger.Info(string.Format("文件路径: {0}", dirPath));

            int count = 0;
            foreach (string f in finder.GetFileFromDirectory(dt, dirPath))
            {
                if (f.Length == 0)
                {                    
                    continue;
                }
                Logger.Info(string.Format("发现文件: {0}, 处理ing", f));
                try
                {
                    importer.ImportDataFromFileWithDate(f, dt);
                }
                catch (Exception e)
                {

                    string errorMsg = string.Format("处理文件时 {0}  时,出现问题： {1}", f, e.Message);
                    string trackMsg = string.Format("StackTrace ： {0}", e.StackTrace.ToString());

                    Logger.Error(errorMsg);
                    Logger.Error(trackMsg);

                }
                count++;
            }
            if (count == 0)
            {
                if (assertHaseFile)
                {
                    Logger.Error(string.Format("未能发现需要的数据文件： {0} {1}", dt.ToString(), info));
                }
                else
                {
                    Logger.Info(string.Format("未能发现需要的数据文件： {0} {1}", dt.ToString(), info));
                }
            }

        }

        public void importManualData(int startYear, int startMonth, int endYear, int endMonth,bool needCalculateSemi = true)
        {
            // 人工站实况数据入库
            DateTime start = new DateTime(startYear, startMonth, 1);
            DateTime end = new DateTime(endYear, endMonth, 1);
            string dirPath = AppSettings["ManualStationDirectory"];
            string dbConnectionString = AppSettings["ConnectionString"];
            IDataFileFinder finder = new ManualStationFinder();
            
            IDataImporter importer = DataImporterFactory.GetManualStationDataImporter(dbConnectionString);
            if (needCalculateSemi)
                importer.AfterDataInDatabase += new EventHandler(CalculateManualSemi);

            DateTime cur = start;
            while (cur <= end)
            {
                importData("手动站 实况数据入库", cur, dirPath, finder, importer,false);
                cur = cur.AddMonths(1);
            }
        }


        public void importSchedule(int startYear, int startMonth, int endYear, int endMonth, bool forceClear)
        {
            DateTime start = new DateTime(startYear, startMonth, 1);
            DateTime end = new DateTime(endYear, endMonth, 1);
            string dbConnectionString = AppSettings["ConnectionString"];

            if (forceClear)
            {
                ScheduleLogRepository logRepository = new ScheduleLogRepository(dbConnectionString);
                logRepository.DeleteRecordWithDateRange( start, end );

                ScheduleRepository repository = new ScheduleRepository(dbConnectionString);
                repository.DeleteRecordWithDateRange(start, end.AddMonths(1).AddDays(-1));
            }


            string dirPath = AppSettings["ScheduleDirectory"];
            IDataFileFinder finder = new ScheduleFinder();
            ScheduleImporter importer = (ScheduleImporter)DataImporterFactory.GetScheduleDataImporter(dbConnectionString);
            DateTime cur = start;
            while (cur <= end)
            {
                importer.Clear();
                importData("排班表入库", cur, dirPath, finder, importer,false);
                importer.SaveEntity(forceClear);
                cur = cur.AddMonths(1);
            }
        }

        public void reimportInvalideData()
        {
            string dbConnectionString = AppSettings["ConnectionString"];
            RealDataLogRepository realDataRepository = new RealDataLogRepository(dbConnectionString);
            if (!realDataRepository.IsTableExist())
                realDataRepository.CreateTable();
            //自动站实况数据入库

            IDataImporter importer = DataImporterFactory.GetAutoStationDataImporter(dbConnectionString);
            importer.AfterDataInDatabase += new EventHandler(CalculateAutoSemi);
            // GetLatestRealData
            RealDataLogRepository logRepository = new RealDataLogRepository(dbConnectionString);
            RealDataLogEntity entity = logRepository.GetLatestRealData(ForeSemiType.Auto);

            //获取重新入库的天数
            string backDate = AppSettings["ReimportBackDate"];

            DateTime lastDate = entity.RealDate;
            DateTime beginDate = lastDate.AddDays(0 - Convert.ToInt32(backDate));
            DateTime endDate = DateTime.Now;
            RealDataLogEntity[] records = logRepository.GetRealDataWithDateRange(ForeSemiType.Auto, beginDate, endDate);
            Logger.Info("重导自动站实况");
            DateTime curDate = beginDate;
            List<DateTime> missedDate = new List<DateTime>();
            foreach (RealDataLogEntity record in records)
            {
                while (curDate.Year != record.RealDate.Year || curDate.Month != record.RealDate.Month || curDate.Day != record.RealDate.Day)
                {
                    missedDate.Add(curDate.Date);
                    curDate = curDate.AddDays(1);
                }
                curDate = curDate.AddDays(1);

                if (record.NeedReimport)
                {
                    Logger.Info("导入文件" + record.FilePath); 
                    importer.ImportDataFromFile(record.FilePath);
                }

            }

            while (curDate <= endDate)
            {
                missedDate.Add(curDate.Date);
                curDate = curDate.AddDays(1);
            }


            //导入缺失数据
            string dirPath = AppSettings["AutoStationDirectory"];
            IDataFileFinder finder = new AutoStationFinder();
            foreach (DateTime dt in missedDate)
            {
                importData("重新入库缺失的自动站实况数据", dt, dirPath, finder, importer,false);
            }
        }

        public void execute(DateTime dt)
        {
            string dbConnectionString = AppSettings["ConnectionString"];

            importCityFore(dbConnectionString, dt);

            importZytCityFore(dbConnectionString, dt);

            importRainFore(dbConnectionString, dt);

            importSiteFore(dbConnectionString, dt);

            importUserSiteFore(dbConnectionString, dt);

            importSdxCityFore(dbConnectionString, dt);

            importRealData(dbConnectionString, dt);
        }

        public void importCityFore(string dbConnectionString, DateTime dt, string configItem = "CityForeDirectory")
        {
            //// 城镇预报文件入库
            string dirPath = AppSettings[configItem];
            IDataFileFinder finder = new NormalCityForeFinder();
            NormalCityForeImporter importer = DataImporterFactory.GetCityForeDataImporter(dbConnectionString);
            Logger.Info("执行城镇预报文件入库操作");
            foreach (KeyValuePair<string, string[]> pair in finder.GetFileListFromDirectory(dt, dirPath))
            {
                if (pair.Value.Length > 0)
                {
                    importer.ClearProcessedData();
                    foreach (string path in pair.Value)
                    {
                        Logger.Info(("发现文件：" + path));
                        importer.ImportDataFromFileWithDate(path, dt);
                    }

                    string filename = Path.GetFileName(pair.Value[0]);
                    ForeClockType clock = importer.GetClockByFileName(filename);
                    ForeSendpointType sendpoint = importer.GetSendpointByFileName(filename);
                    importer.SaveDataToDataBase(dt, clock, sendpoint);
                }
            }
        }

        public void importZytCityFore(string dbConnectionString, DateTime dt, string configItem = "ZytCityForeDirectory")
        {
            //// 城镇预报文件入库
            string dirPath = AppSettings[configItem];
            IDataFileFinder finder = new ZytCityForeFinder();
            ZytCityForeImporter importer = DataImporterFactory.GetZytCityForeDataImporter(dbConnectionString);

            DirectoryInfo thisOne = new DirectoryInfo(dirPath);
            string date = dt.ToString("yyyyMM");
            string date0 = dt.AddDays(-1).ToString("yyyyMM");
            Logger.Info("执行国家局指导预报文件入库操作");
            if (Convert.ToInt32(date) == Convert.ToInt32(date0))
            {
                string userdir = dirPath; //string.Format("{0}/{1}/", dirPath, date);
                
                foreach (KeyValuePair<string, string[]> pair in finder.GetFileListFromDirectory(dt, userdir))
                {
                    if (pair.Value.Length > 0)
                    {
                        importer.ClearProcessedData();
                        foreach (string path in pair.Value)
                        {
                            Logger.Info("发现文件：" + path);
                            importer.ImportDataFromFileWithDate(path, dt);
                        }

                        string filename = Path.GetFileName(pair.Value[0]);
                        ForeClockType clock = importer.GetClockByFileName(filename);
                        ForeSendpointType sendpoint = importer.GetSendpointByFileName(filename);
                        if (sendpoint == ForeSendpointType.H15)
                        {
                            importer.SaveDataToDataBase(dt, clock, sendpoint);
                            importer.SaveDataToDataBase(dt, clock, ForeSendpointType.H16);
                        }
                        else
                        {
                            importer.SaveDataToDataBase(dt, clock, sendpoint);
                        }
                    }
                }
            }
            else
            {
                string userdir = dirPath; 
                //string userdir = string.Format("{0}/{1}/", dirPath, date);                
                foreach (KeyValuePair<string, string[]> pair in finder.GetFileListFromDirectory(dt, userdir))
                {
                    if (pair.Value.Length > 0)
                    {
                        importer.ClearProcessedData();
                        foreach (string path in pair.Value)
                        {
                            Logger.Info("发现文件：" + path);
                            importer.ImportDataFromFileWithDate(path, dt);
                        }

                        string filename = Path.GetFileName(pair.Value[0]);
                        ForeClockType clock = importer.GetClockByFileName(filename);
                        ForeSendpointType sendpoint = importer.GetSendpointByFileName(filename);
                        if (sendpoint == ForeSendpointType.H15)
                        {
                            importer.SaveDataToDataBase(dt, clock, sendpoint);
                            importer.SaveDataToDataBase(dt, clock, ForeSendpointType.H16);
                        }
                        else
                        {
                            importer.SaveDataToDataBase(dt, clock, sendpoint);
                        }
                    }
                }
                //userdir = string.Format("{0}/{1}/", dirPath, date0);
                userdir = dirPath;
                Logger.Info("国家局指导预报文件入库！");
                foreach (KeyValuePair<string, string[]> pair in finder.GetFileListFromDirectory(dt, userdir))
                {
                    if (pair.Value.Length > 0)
                    {
                        importer.ClearProcessedData();
                        foreach (string path in pair.Value)
                        {
                            Logger.Info("发现文件：" + path);
                            importer.ImportDataFromFileWithDate(path, dt);
                        }

                        string filename = Path.GetFileName(pair.Value[0]);
                        ForeClockType clock = importer.GetClockByFileName(filename);
                        ForeSendpointType sendpoint = importer.GetSendpointByFileName(filename);
                        importer.SaveDataToDataBase(dt, clock, sendpoint);
                    }
                }
            }
        }

        /// <summary>
        /// 降水等值线
        /// </summary>
        public void importRainFore(string dbConnectionString, DateTime dt, string configItem = "RainForeDirectory_ZhongQi")
        {
            string dirPath = AppSettings[configItem];
            IDataFileFinder finder = new RainForeFinder();
            IDataImporter importer = DataImporterFactory.GetRainForeDataImporter(dbConnectionString);
            importData("降水等值线中期文件！", dt, dirPath, finder, importer,true);
            dirPath = AppSettings["RainForeDirectory_DuanQi"];
            importData("降水等值线短期文件！", dt, dirPath, finder, importer,true);
        }

        public void importRealData(string dbConnectionString, DateTime dt,bool needCalculateSemi = true, string configItem = "AutoStationDirectory")
        {
            //自动站实况数据入库
            string dirPath = AppSettings[configItem];
            IDataFileFinder finder = new AutoStationFinder();
            IDataImporter importer = DataImporterFactory.GetAutoStationDataImporter(dbConnectionString);
            if( needCalculateSemi)
                importer.AfterDataInDatabase += new EventHandler(CalculateAutoSemi);
            importData("自动站实况数据入库", dt, dirPath, finder, importer,true);
        }

        public void importRealData(DateTime start, DateTime end, bool needCalculateSemi = true)
        {
            // 人工站实况数据入库            
            string dirPath = AppSettings["AutoStationDirectory"];
            string dbConnectionString = AppSettings["ConnectionString"];
            IDataFileFinder finder = new AutoStationFinder();

            IDataImporter importer = DataImporterFactory.GetAutoStationDataImporter(dbConnectionString);
            if (needCalculateSemi)
                importer.AfterDataInDatabase += new EventHandler(CalculateAutoSemi);

            DateTime cur = start;
            while (cur <= end)
            {
                importData("自动站 实况数据入库", cur, dirPath, finder, importer,true);
                cur = cur.AddDays(1);
            }
        }


        public void importSiteFore(string dbConnectionString, DateTime dt, string configItem = "StSiteForeDirectory")
        {
            //指导站点预报
            string dirPath = AppSettings[configItem];
            IDataFileFinder finder = new SiteForeFinder();
            IDataImporter importer = DataImporterFactory.GetStSiteForeDataImporter(dbConnectionString);
            importData("指导站点预报 短期 文件入库！", dt, dirPath, finder, importer, true);
            dirPath = AppSettings["StSiteForeDirectory_Zhongqi"];
            importData("指导站点预报 中期 文件入库！", dt, dirPath, finder, importer,true);
        }

        public void importUserSiteFore(string dbConnectionString, DateTime dt, string configItem = "UserSiteForeDirectory")
        {
            //指导站点个人预报文件
            //获取所有子目录
            IDataFileFinder finder = new UserSiteForeFinder();

            string dirPath = AppSettings[configItem];
            DirectoryInfo thisOne = new DirectoryInfo(dirPath);
            
            foreach (DirectoryInfo sub in thisOne.GetDirectories())
            {
                string userdir = string.Format("{0}/{1}/{2}/", sub.FullName, "zdzd", dt.Year.ToString());

                if (Directory.Exists(userdir))
                {
                    //需要先检查一下该用户是否存在
                    IDataImporter importer = DataImporterFactory.GetUserSiteForeDataImporter(dbConnectionString, sub.Name);
                    importData(string.Format("指导站点个人 {0} 的预报文件！", sub.FullName), dt, sub.FullName, finder, importer,false);
                }
            }
        }



        

        public void importSdxCityFore(string dbConnectionString, DateTime dt)
        {
            /*
            #region 市代县指导预报文件入库
            dirPath = AppSettings["SdxCityForeDirectory"];
            finder = new SdxCityForeFinder();
            importer = DataImporterFactory.GetSdxCityForeDataImporter(dbConnectionString);
            files = finder.GetFileFromDirectory(dt, dirPath);
            foreach (string f in files)
            {
                importer.ImportDataFromFileWithDate(f, dt);
            }
            #endregion
            */
        }

        public void CalculateAutoSemi(object sender, EventArgs args)
        {
            FindDataEventArgs findArgs = args as FindDataEventArgs;
            if (findArgs.Data is RainRealEntity)
            {
                RainRealEntity rainEntity = findArgs.Data as RainRealEntity;
                semier.CalculatSemiWithRainRecord(rainEntity, ForeSemiType.Auto, ForeSemiType.Auto);
            }
            else
            {
                TempRealEntity tempEntity = findArgs.Data as TempRealEntity;
                semier.CalculatSemiWithTempRecord(tempEntity, ForeSemiType.Auto, ForeSemiType.Auto);
            }
        }

        public void CalculateManualSemi(object sender, EventArgs args)
        {
            FindDataEventArgs findArgs = args as FindDataEventArgs;
            if (findArgs.Data is RainRealEntity)
            {
                RainRealEntity rainEntity = findArgs.Data as RainRealEntity;
                semier.CalculatSemiWithRainRecord(rainEntity, ForeSemiType.Auto, ForeSemiType.Manual);
            }
            else
            {
                TempRealEntity tempEntity = findArgs.Data as TempRealEntity;
                semier.CalculatSemiWithTempRecord(tempEntity, ForeSemiType.Auto, ForeSemiType.Manual);
            }
        }

        /// <summary>
        /// 补足降水等值线数据
        /// </summary>
        public void CompleteRainForeLackFile()
        {
            string dbConnectionString = AppSettings["ConnectionString"];
            semier = new Semier(dbConnectionString, new ForeRepository[] { ForeRepositoryFactory.RainForeRepository(dbConnectionString) });
            RainRealRepository autoRainRealRepository = RainRealRepositoryFactory.AutoStationRainRealRepository(dbConnectionString);
            RainRealRepository manualRainRealRepository = RainRealRepositoryFactory.ManualRainRealRepository(dbConnectionString);
            DateTime start = new DateTime(2011, 5, 21);
            DateTime end = new DateTime(2011, 12, 31);
            DateTime cur = start;
            while (cur <= end)
            {
                importRainFore(dbConnectionString, cur);
                //计算semi
                RainRealEntity[] entities = autoRainRealRepository.GetEntitiesWithDate(cur);
                foreach (RainRealEntity entity in entities)
                {
                    semier.CalculatSemiWithRainRecord(entity, ForeSemiType.Auto, ForeSemiType.Auto);
                }

                entities = manualRainRealRepository.GetEntitiesWithDate(cur);
                foreach (RainRealEntity entity in entities)
                {
                    semier.CalculatSemiWithRainRecord(entity, ForeSemiType.Auto, ForeSemiType.Manual);
                }
                cur = cur.AddDays(1);
            }
        }

        /// <summary>
        /// 初足指导站点数据
        /// </summary>
        public void CompleteStSiteForeLackFile()
        {
            string dbConnectionString = AppSettings["ConnectionString"];

            DateTime start = new DateTime(2012, 1, 7);
            DateTime end = new DateTime(2012, 1, 7);
            DateTime cur = start;
            while (cur <= end)
            {
                importSiteFore(dbConnectionString, cur);

                cur = cur.AddDays(1);
            }

            ReCalSemi( start,end, dbConnectionString,new List<ForeRepository>() { ForeRepositoryFactory.StSiteForeRepository(dbConnectionString) });
        }

        /// <summary>
        /// 初足指导站点数据
        /// </summary>
        public void CompleteSiteForeLackFile(DateTime start, DateTime end, bool deleteOldData)
        {

            string dbConnectionString = AppSettings["ConnectionString"];

            string dirPath = AppSettings["UserSiteForeDirectory"];
            DirectoryInfo thisOne = new DirectoryInfo(dirPath);
            List<ForeRepository> repositories = new List<ForeRepository>();
            foreach (DirectoryInfo sub in thisOne.GetDirectories())
            {
                ForeRepository rep = ForeRepositoryFactory.SiteForeRepository(dbConnectionString, sub.Name);
                if (deleteOldData)
                    rep.DeleteRecordWithDateRange(start, end);
                repositories.Add(rep);
            }

            DateTime cur = start;
            while (cur <= end)
            {
                importUserSiteFore(dbConnectionString, cur);
               
                cur = cur.AddDays(1);
            }

            ReCalSemi(start, end,dbConnectionString,repositories);
        }

        /// <summary>
        /// 针对性导入错误文件
        /// </summary>
        public void reimportErrorFile()
        {
            string dbConnectionString = AppSettings["ConnectionString"];
            importCityFore(dbConnectionString, new DateTime(2012, 4, 19), "ErrorFileDirectory");

            //根据文件夹内容，获取所有的用户名称及其表名
            semier = new Semier(dbConnectionString, new ForeRepository[] { ForeRepositoryFactory.NormalCityForeRepository(dbConnectionString) });

            RainRealRepository autoRainRealRepository = RainRealRepositoryFactory.AutoStationRainRealRepository(dbConnectionString);
            RainRealRepository manualRainRealRepository = RainRealRepositoryFactory.ManualRainRealRepository(dbConnectionString);

            TempRealRepository autoTempRealRepository = TempRealRepositoryFactory.AutoStationTempRealRepository(dbConnectionString);
            TempRealRepository manualTempRealRepository = TempRealRepositoryFactory.ManualTempRealRepository(dbConnectionString);

            DateTime start = new DateTime(2012, 4, 19);
            DateTime end = new DateTime(2012, 4, 30);
            DateTime cur = start;
            while (cur <= end)
            {
                RainRealEntity[] rainEntities = autoRainRealRepository.GetEntitiesWithDate(cur);
                foreach (RainRealEntity entity in rainEntities)
                {
                    semier.CalculatSemiWithRainRecord(entity, ForeSemiType.Auto, ForeSemiType.Auto);
                }

                rainEntities = manualRainRealRepository.GetEntitiesWithDate(cur);
                foreach (RainRealEntity entity in rainEntities)
                {
                    semier.CalculatSemiWithRainRecord(entity, ForeSemiType.Auto, ForeSemiType.Manual);
                }


                TempRealEntity[] tempEntities = autoTempRealRepository.GetEntitiesWithDate(cur);
                foreach (TempRealEntity entity in tempEntities)
                {
                    semier.CalculatSemiWithTempRecord(entity, ForeSemiType.Auto, ForeSemiType.Auto);
                }

                tempEntities = manualTempRealRepository.GetEntitiesWithDate(cur);
                foreach (TempRealEntity entity in tempEntities)
                {
                    semier.CalculatSemiWithTempRecord(entity, ForeSemiType.Auto, ForeSemiType.Manual);
                }
                cur = cur.AddDays(1);
            }


            importZytCityFore(dbConnectionString, new DateTime(2012, 5, 16), "ErrorFileDirectory");
            importZytCityFore(dbConnectionString, new DateTime(2012, 5, 28), "ErrorFileDirectory");
            //根据文件夹内容，获取所有的用户名称及其表名
            semier = new Semier(dbConnectionString, new ForeRepository[] { ForeRepositoryFactory.ZytCityForeRepository(dbConnectionString) });

            autoRainRealRepository = RainRealRepositoryFactory.AutoStationRainRealRepository(dbConnectionString);
            manualRainRealRepository = RainRealRepositoryFactory.ManualRainRealRepository(dbConnectionString);

            autoTempRealRepository = TempRealRepositoryFactory.AutoStationTempRealRepository(dbConnectionString);
            manualTempRealRepository = TempRealRepositoryFactory.ManualTempRealRepository(dbConnectionString);

            start = new DateTime(2012, 5, 16);
            end = new DateTime(2012, 5, 31);
            cur = start;
            while (cur <= end)
            {
                RainRealEntity[] rainEntities = autoRainRealRepository.GetEntitiesWithDate(cur);
                foreach (RainRealEntity entity in rainEntities)
                {
                    semier.CalculatSemiWithRainRecord(entity, ForeSemiType.Auto, ForeSemiType.Auto);
                }

                rainEntities = manualRainRealRepository.GetEntitiesWithDate(cur);
                foreach (RainRealEntity entity in rainEntities)
                {
                    semier.CalculatSemiWithRainRecord(entity, ForeSemiType.Auto, ForeSemiType.Manual);
                }


                TempRealEntity[] tempEntities = autoTempRealRepository.GetEntitiesWithDate(cur);
                foreach (TempRealEntity entity in tempEntities)
                {
                    semier.CalculatSemiWithTempRecord(entity, ForeSemiType.Auto, ForeSemiType.Auto);
                }

                tempEntities = manualTempRealRepository.GetEntitiesWithDate(cur);
                foreach (TempRealEntity entity in tempEntities)
                {
                    semier.CalculatSemiWithTempRecord(entity, ForeSemiType.Auto, ForeSemiType.Manual);
                }
                cur = cur.AddDays(1);
            }
        }

        public void CompleteCityFore(DateTime start, DateTime end)
        {
            string dbConnectionString = AppSettings["ConnectionString"];

            List<ForeRepository> repositories = new List<ForeRepository>(){ForeRepositoryFactory.NormalCityForeRepository(dbConnectionString)
            };

            DateTime cur = start;
            while (cur <= end)
            {
                importCityFore(dbConnectionString, cur);
                cur = cur.AddDays(1);
            }

            ReCalSemi(start, end, dbConnectionString, repositories);

        }

        public void CompleteSiteFore(DateTime start, DateTime end)
        {
            string dbConnectionString = AppSettings["ConnectionString"];

            List<ForeRepository> repositories = new List<ForeRepository>(){ForeRepositoryFactory.StSiteForeRepository(dbConnectionString)
            };

            DateTime cur = start;
            while (cur <= end)
            {
                importSiteFore(dbConnectionString, cur);
                cur = cur.AddDays(1);
            }

            ReCalSemi(start, end, dbConnectionString, repositories);

        }

        public void CompleteZytFore(DateTime start, DateTime end)
        {
            string dbConnectionString = AppSettings["ConnectionString"];

            List<ForeRepository> repositories = new List<ForeRepository>(){ForeRepositoryFactory.ZytCityForeRepository(dbConnectionString)
            };

            DateTime cur = start;
            while (cur <= end)
            {
                importZytCityFore(dbConnectionString, cur);
                cur = cur.AddDays(1);
            }

            ReCalSemi(start, end, dbConnectionString, repositories);
        }

        public void ReCalSemi(DateTime start, DateTime end,string dbConnectionString, List<ForeRepository> repositories = null, int addDays = 7)
        {
            //根据文件夹内容，获取所有的用户名称及其表名
            if (repositories != null)
                semier = new Semier(dbConnectionString, repositories.ToArray());
            else
                semier = new Semier(dbConnectionString);

            string tables = "All Fore";
            if (repositories != null)
            {
                List<string> table_names = new List<string>();
                foreach (ForeRepository repository in repositories)
                {
                    table_names.Add(repository.TableName);
                }
                tables = string.Join(",", table_names.ToArray());
            }
             Logger.Info(string.Format("初始化Fore表: {0}, 将会重新计算这些表的Semi",tables));

            RainRealRepository autoRainRealRepository = RainRealRepositoryFactory.AutoStationRainRealRepository(dbConnectionString);
            RainRealRepository manualRainRealRepository = RainRealRepositoryFactory.ManualRainRealRepository(dbConnectionString);

            TempRealRepository autoTempRealRepository = TempRealRepositoryFactory.AutoStationTempRealRepository(dbConnectionString);
            TempRealRepository manualTempRealRepository = TempRealRepositoryFactory.ManualTempRealRepository(dbConnectionString);

            DateTime cur = start;
            end = end.AddDays(addDays);
            if (end > DateTime.Now)
                end = DateTime.Now;
            while (cur <= end)
            {
                Logger.Info(string.Format("计算 {0} 的Semi", cur.ToString("yyyy-MM-dd")));

                RainRealEntity[] rainEntities = autoRainRealRepository.GetEntitiesWithDate(cur);
                if (rainEntities.Length == 0)
                    Logger.Error("找不到自动站降水实况数据的记录，无法计算Semi");
                foreach (RainRealEntity entity in rainEntities)
                {
                    semier.CalculatSemiWithRainRecord(entity, ForeSemiType.Auto, ForeSemiType.Auto);
                }

                rainEntities = manualRainRealRepository.GetEntitiesWithDate(cur);
                if (rainEntities.Length == 0)
                    Logger.Error("找不到人工站降水实况数据的记录，无法计算Semi"); 
                foreach (RainRealEntity entity in rainEntities)
                {
                    semier.CalculatSemiWithRainRecord(entity, ForeSemiType.Auto, ForeSemiType.Manual);
                }


                TempRealEntity[] tempEntities = autoTempRealRepository.GetEntitiesWithDate(cur);
                if (tempEntities.Length == 0)
                    Logger.Error("找不到自动站气温实况数据的记录，无法计算Semi");
                foreach (TempRealEntity entity in tempEntities)
                {
                    semier.CalculatSemiWithTempRecord(entity, ForeSemiType.Auto, ForeSemiType.Auto);
                }

                tempEntities = manualTempRealRepository.GetEntitiesWithDate(cur);
                if (tempEntities.Length == 0)
                    Logger.Error("找不到人工站气温实况数据的记录，无法计算Semi"); 
                foreach (TempRealEntity entity in tempEntities)
                {
                    semier.CalculatSemiWithTempRecord(entity, ForeSemiType.Auto, ForeSemiType.Manual);
                }

                cur = cur.AddDays(1);
            }
        }


    }
}
